package com.panshi.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.panshi.tools.ResponseData;

import javax.servlet.http.HttpSession;
import java.util.Date;

public class GlobalInterceptor implements Interceptor {
    public void intercept(Invocation invocation) {

        Controller controller = invocation.getController();// 获得controller信息
        String actionKey = invocation.getActionKey();//获得请求路径
        HttpSession session = controller.getSession();
        String packageId = controller.getHeader("Package-Id");//商店-版本-包名-操作系统
        if (null != packageId) {

            String[] param = packageId.split("-");
            try {
                String store = param[0];
                String version = param[1];
                String packageName = param[2];
                String os = param[3];
                controller.setAttr("store", store).setAttr("version", version).setAttr("packageName", packageName)
                        .setAttr("os", os).setAttr("packageId",packageId);
            } catch (Exception e) {
                controller.renderJson(ResponseData.notFound());
                return;
            }
            System.out.println("#############开始执行 Action  "+new Date());
            //防止重复提交功能
            if(null!=session.getAttribute(actionKey))
            {
                controller.renderJson(ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY,"请求处理中,请不要重复提交!"));
                return;
            }
            session.setAttribute(actionKey,actionKey);
            invocation.invoke();
            System.out.println("################执行完毕,清理session"+new Date());
            session.removeAttribute(actionKey);
        } else
            controller.renderJson(ResponseData.notFound());
    }
}
